<template>
    <div>
        <h1>扫一扫二维码</h1>
        <video ref="video" width="800" height="675"></video>
        <div>{{ result }}</div>
        <button @click="stopScan">停止扫描</button>

    </div>
</template>
    
<script>
import jsQR from 'jsqr'

export default {
    data() {
        return {
            result: ''
        }
    },
    mounted() {
        this.startScan()
    },
    methods: {
        startScan() {
            const video = this.$refs.video
            navigator.mediaDevices.getUserMedia({ video: true })
                .then(stream => {
                    video.srcObject = stream
                    video.play()

                    // 处理视频帧
                    this.scanTask = setInterval(() => {
                        // 将video截图存储到canvas中
                        const canvas = document.createElement('canvas')
                        canvas.width = video.videoWidth
                        canvas.height = video.videoHeight
                        canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height)

                        // 解析canvas中的QR码
                        const imageData = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height)
                        const code = jsQR(imageData.data, imageData.width, imageData.height)

                        if (code) {
                            // 当解析成功时，停止定时任务并显示结果
                            clearInterval(this.scanTask)
                            this.result = '解析的数据：' + 1
                            if ((this.result = "Accounts")) {
                                this.$router.push({
                                    path: "/Accounts",
                                });
                            }
                        }
                    }, 1000)
                })
                .catch(err => {
                    console.error('Error opening camera.', err)
                })
        },
        stopScan() {
            clearInterval(this.scanTask)
            const video = this.$refs.video
            video.pause()
        }
    }
}
</script>
<style ></style>